package com.chen.service.impl;

import com.chen.entity.QQUser;
import com.chen.entity.dto.RegisterDto;
import com.chen.entity.vo.ResultCodeEnum;
import com.chen.handler.MyException;
import com.chen.mapper.QQUserMapper;
import com.chen.service.QQUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class QQUserServiceImpl implements QQUserService {
    @Autowired
    private QQUserMapper qQuserMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 登录
     * @param qqUser
     */
    @Override
    public void login(QQUser qqUser) {
        String regex = "^1[3-9]\\d{9}$";
        QQUser databaseQQUser=null;
        if(qqUser.getQqNum().toString().matches(regex)){
             qqUser.setPhone(qqUser.getQqNum().toString());
             databaseQQUser= qQuserMapper.selectQQUserByPhone(qqUser.getPhone());
        }else {
            databaseQQUser= qQuserMapper.selectQQUserByQQNum(qqUser.getQqNum());
        }
        //根据qq号查询
        if(databaseQQUser==null){
            throw  new MyException(ResultCodeEnum.UserName_NO);
        }
        String inputPassword = qqUser.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(inputPassword.getBytes(StandardCharsets.UTF_8));
        if(!md5Password.equals(databaseQQUser.getPassword())){
            throw  new MyException(ResultCodeEnum.Password_NO);
        }
        //登录成功
    }

//    public static void main(String[] args) {
//        String md5Password = DigestUtils.md5DigestAsHex("cgj666".getBytes(StandardCharsets.UTF_8));
//        System.out.println(md5Password);
//    }
    /**
     * 注册
     *
     * @param registerDto
     * @return
     */
    @Override
    public Long register(RegisterDto registerDto) {
        //对比验证码
        String webCode = registerDto.getCode();

        //获取对应手机号存储的验证码
        String redisCode = redisTemplate.opsForValue().get("phone:code" + webCode);
        if(redisCode==null){
            new MyException(ResultCodeEnum.Code_ERROR);
        }
        //生成一个账号
        long qqNum = System.currentTimeMillis();
        //获取用户输入的密码
        String password = registerDto.getPassword();
        //加密
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //封装数据
        QQUser qqUser = new QQUser();
        qqUser.setPassword(md5Pass);
        qqUser.setQqNum(qqNum);
        qqUser.setPhone(registerDto.getPhone());
       //保存到数据库
        qQuserMapper.save(qqUser);
        return qqNum;
    }
}
